import { Injectable } from '@angular/core';
import { throwError, of } from 'rxjs';
import {FavoriteGroup, UserInfo} from 'src/app/@shared/models/UserInfo';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {api} from "./config/api";
import {BBYUtils} from "@shared/utils/BBYUtils";
import {Result} from "@shared/models/Result";
import {NzMessageService} from "ng-zorro-antd/message";
@Injectable({
  providedIn: 'root',
})
export class AuthService {
  defHeaders :any;
  constructor(
    private http: HttpClient,
    private message:NzMessageService
  ) {
    this.defHeaders = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8')
  }
  avatarUrl=`${api.getAvatar}/${this.getUserInfo()?.userId}`
  userInfo:UserInfo|undefined;
  // options: {
  //   headers?: HttpHeaders | {[header: string]: string | string[]},
  //   observe?: 'body' | 'events' | 'response',
  //     params?: HttpParams|{[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>},
  //   reportProgress?: boolean,
  //     responseType?: 'arraybuffer'|'blob'|'json'|'text',
  //     withCredentials?: boolean,
  // }
  login(type:number,data:{}) {
    console.log(data)
    return this.http.post(type==0? api.login:api.loginByCaptcha, data, {
      responseType:'json'
    });
  }

  public static getAuthHeaders(){
    let token = localStorage.getItem('token');
    return token? new HttpHeaders().set('token', token):{}
  }

  /**
   * 读取本地用户信息
   */
  public static readUserInfo() {
    let str = localStorage.getItem('userInfo');
    return str? JSON.parse(str):undefined;
  }
  /**
   * 保存本地用户信息
   */
  public static saveUserInfo(data: UserInfo) {
    // console.log('save',data)
    localStorage.setItem('userInfo', JSON.stringify(data));
    AuthService.saveFavorites(data.favorites)
  }

  /**
   * 保存本地收藏
   */
  public static saveFavorites(data: FavoriteGroup[]) {
    localStorage.setItem('favorites', JSON.stringify(data));
  }
  /**
   * 读取本地收藏
   */
  public static getFavorites() {
    let str = localStorage.getItem('favorites');
    return str? JSON.parse(str):undefined;
  }
  logout() {
    let token = localStorage.getItem('token');
    if (token) {
      this.http.post(api.logout,{},{headers:new HttpHeaders().set('token', token)}).subscribe(console.log)
    }
    this.userInfo=undefined;
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');
  }

  saveLoginStatus(data:{token:string,userInfo:UserInfo}) {
    localStorage.setItem('token', data.token);
    AuthService.saveUserInfo(data.userInfo)
  }

  isUserLoggedIn() {
    if (this.getUserInfo()) {
      return true;
    } else {
      return false;
    }
  }

  register(data: {username:string; email: string; password: string; captcha:string}) {
    console.log('register：',data)
    return this.http.post<Result>(api.register,data);
  }

  getUserInfo() {
    if (this.userInfo){
      return this.userInfo
    }
    this.userInfo = AuthService.readUserInfo()
    return this.userInfo;
  }

  sendEmailCaptcha(data : {email:string, imgId:string, imgValue:string}){
    console.log('sendEmailCaptcha：',data)
    return this.http.post<Result>(api.captchaEmail,data,{});
  }
  checkUsername(username: string) {
    console.log('checkUsername：',username)
    return this.http.get<Result>(api.checkName+'/'+username);
  }

  // 修改邮箱，发送验证码到邮箱
  mailCaptcha(mail:string){
    return this.http.get<Result>(api.mailCaptcha+`?mail=${mail}`, BBYUtils.createHeadersOption());
  }
  mailEdit(data:{newMail: string, mailToken: string, captcha: string}) {
    return this.http.post<Result>(api.mailEdit,data, BBYUtils.createHeadersOption());
  }
  // 邮箱的token
  getMailToken(mail: string, value: string) {
    return this.http.get<Result>(api.mailToken+`?mail=${mail}&value=${value}`, BBYUtils.createHeadersOption());
  }
  checkEmail(mail: any) {
    console.log('checkEmail：',mail)
    return this.http.get<Result>(api.checkEmail+'/'+mail);
  }

  flashUserInfo() {
    BBYUtils.handelResult(
      this.http.get<Result>(api.userInfo, BBYUtils.createHeadersOption()),
      res => {
        AuthService.saveUserInfo(res.data)
        this.userInfo=res.data
        this.avatarUrl=`${api.getAvatar}/${this.userInfo?.userId}`
      },
        res => {
          this.message.error(res.msg)
      }
    )
  }

  passwdEdit(data: { currentPw: any; newPw: any }) {
    return this.http.post<Result>(api.passwdEdit,data, BBYUtils.createHeadersOption());
  }

  usernameEdit(username: string) {
    return this.http.post<Result>(api.usernameEdit+`?username=${username}`,{}, BBYUtils.createHeadersOption());
  }

  uploadCustom(key: string, value: string) {
    BBYUtils.handelResult(
      this.http.post<Result>(api.customEdit+`/${key}?value=${value}`,{}, BBYUtils.createHeadersOption()),
      res => {
        this.message.success('已修改！')
        if (this.userInfo){
          switch (key){
            case 'sex':this.userInfo.sex=value;break;
            case 'signature':this.userInfo.signature=value;break;
            case 'birthday':this.userInfo.birthday=value;break;
          }
          AuthService.saveUserInfo(this.userInfo)
        }
      },
      res => {
        this.message.error(res.msg)
      }
    )
  }
}
